package com.googlecode.openrtp.grizzly;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.googlecode.openrtp.grizzly.util.BufferUtil;
import static org.mockito.Mockito.*;

/**
 *
 * @author jocke
 */
public final class Fixture {

    private Fixture() {
    }

    public static BufferUtil getMockedBufferUtil() throws UnsupportedEncodingException {

        BufferUtil bufferUtil = mock(BufferUtil.class);

        when(bufferUtil.allocate(any(FilterChainContext.class), anyInt())).thenAnswer(new Answer<ByteBuffer>() {
            @Override
            public ByteBuffer answer(InvocationOnMock invocation) throws Throwable {
                return ByteBuffer.allocate((int) invocation.getArguments()[1]);
            }
        });

        when(bufferUtil.getUnsignedIntAsLong(isA(Buffer.class), isA(ByteBuffer.class))).thenCallRealMethod();
        when(bufferUtil.readString(isA(Buffer.class), anyInt())).thenCallRealMethod();
        when(bufferUtil.allocateBuffer(any(FilterChainContext.class), anyInt())).then(
                new Answer<Buffer>() {
                    @Override
                    public Buffer answer(InvocationOnMock invocation) throws Throwable {
                        return allocate((int) invocation.getArguments()[1]);
                    }
                });
        return bufferUtil;
    }

    public static Buffer allocate(int size) {
        return org.glassfish.grizzly.memory.MemoryManager.DEFAULT_MEMORY_MANAGER.allocate(size);
    }
}
